package sjtu.ist.warehouse4ws.action;

import java.util.Map;

import sjtu.ist.warehouse4ws.model.User;
import sjtu.ist.warehouse4ws.service.LoginService;
import sjtu.ist.warehouse4ws.tool.BaseAction;
import sjtu.ist.warehouse4ws.tool.ContextSession;

import com.opensymphony.xwork2.ActionContext;
public class LoginAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1246131239446241208L;
	private LoginService LoginService;	
	private String userName;
	private String password;
	private String randCode;
	private boolean success;
	private String message;
	//设置注入业务逻辑组件setter方法
	public void setLoginService(LoginService loginService) {
		this.LoginService = loginService;
	}
	public String getRandCode() {
		return randCode;
	}

	public void setRandCode(String randCode) {
		this.randCode = randCode;
	}

	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isSuccess() {
		  return success;
	}
	public void setSuccess(boolean success) {
		  this.success = success;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	//处理用户请求的execute方法
	public String execute() throws Exception {
		//session调用
		ActionContext actionContext=ActionContext.getContext();
		Map session=actionContext.getSession();
		boolean randCode=false;
		if(session.get("rand").toString().equals(getRandCode()))
			randCode=true;
		// 调用业务逻辑组件的regist方法来处理请求?
		if(!randCode){
			this.success=false;
			this.message="验证码输入有误";
		}else{
			User user=LoginService.login(getUserName(), getPassword());
			if(user!=null){
//				ActionContext actionContext=ActionContext.getContext();
//				Map session=(Map)(actionContext.getSession().get(ActionContext.SESSION));

				session.put("login", "yes");
				
				session.put("user_id" , user.getId());
				session.put("user_name" , user.getName());
				session.put("user_company" , user.getCompany());
				session.put("user_password", user.getPassword());
				session.put("user_type" , user.getType());
				session.put("user", user);
				
				ContextSession.userId=user.getId();
				ContextSession.userName=user.getName();
				ContextSession.userCompany=user.getCompany();
				ContextSession.userType=user.getType();
				
				this.message="main.jsp";
				this.success=true;
			}else{
				this.success=false;
				this.message="输入有误";
			}
		}
		return SUCCESS;
	}
}
